import { isFunction } from 'lodash';
import OpenAI from 'openai';

export const sendMessageV2 = async ({ messages, baseURL, apiKey, model }, continueCallback, sendDestroy) => {
  const openai = new OpenAI({
    baseURL: baseURL ?? 'https://ark.cn-beijing.volces.com/api/v3',
    apiKey: apiKey ?? '572fd2fd-0cc0-443c-a278-6e5271d942ed', // 替换为你的实际 API Key
  });

  const stream = await openai.chat.completions.create({
    messages: messages.map(({ role, content }) => ({ role, content })),
    model: model ?? 'deepseek-v3-250324',
    stream: true,
  });

  if (isFunction(sendDestroy)) {
    sendDestroy({
      destroy: () => {
        stream.controller.abort();
      },
    });
  }

  let content = '';
  for await (const chunk of stream) {
    const choice = chunk.choices[0];
    if (choice.delta?.content) {
      continueCallback(choice.delta.content);
      content = content + choice.delta.content;
    }
  }
  return content;
};
